<!DOCTYPE html>
<html>
    <head>
        <title>WebSocket Echo Client</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!--<script type='text/javascript' src='js/jquery-1.10.2.min.js'></script>-->
    </head>
    <body>
        <div id="output"></div>

        <script>
            //Initialize WebSocket connection and event handlers
            function setup() {
                output = document.getElementById('output');
                ws = new WebSocket("ws://echo.websocket.org/echo");

                //Listen for the connection open event then call the sendMessage function
                ws.onopen = function(e) {
                    log('Connected');
                    sendMessage('Hello WebSocket');
                };

                //Listen for the close connection event
                ws.onclose = function(e) {
                    log('Disconnected: ' + e.reason);
                };

                //Listen for connection errors
                ws.onerror = function(e) {
                    log('Error!');
                };

                //Listen for new messages arriving at the client
                ws.onmessage = function(e) {
                    log('Message received: ' + e.data);
                    //Close the socket once one message has arrived
                    ws.close();
                };
            }
            
            //Send a message on the WebSocket
            function sendMessage(msg){
                ws.send(msg);
                log('Message sent');
            }
            
            //Display logging information in the document
            function log(s){
                var p = document.createElement('p');
                p.style.wordWrap = 'break-word';
                p.textContent = s;
                output.appendChild(p);
                
                //Also log information on the JavaScript console
                console.log(s);
            }
            
            //Starting running the example
            setup();
        </script>
    </body>
</html>
